# This file is part of ModularBot.
# Copyright (C) 2005 Pierre Ducroquet (pierre.linux59@wanadoo.fr)

# ModularBot is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# ModularBot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with ModularBot; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import xml.sax.handler
import xml.sax

class IRCConf (xml.sax.handler.ContentHandler):
	def __init__ (self, filename):
		for attr in ["nick", "url", "channel", "versionNum", "versionEnv", "versionName", "ident", "realname", "rights", "charset", "bind"]:
			setattr(self, attr, "")
		self.port = 0
		self.currentPath = ""
		self.logics_startup = []
		self.logons = []
		self.filename = filename
		self.parse()
	
	def parse (self):
		parser = xml.sax.make_parser()
		parser.setContentHandler(self)
		parser.parse(self.filename)
	
	def characters (self, txt):
		txt = txt.strip()
		if self.currentPath == "/bot/logon/eval":
			self.logons.append(str(txt))
	
	def startElement(self, name, attributes):
		if self.currentPath.endswith("/"):
			self.currentPath += name
		else:
			self.currentPath += "/" + name
		if name == "bot":
			for attr in ["nick", "ident", "realname", "rights", "charset"]:
				if attributes.has_key(attr):
					setattr(self, attr, str(attributes[attr]))
		elif name == "version":
			for attr in ["num", "env", "name"]:
				if attributes.has_key(attr):
					setattr(self, "version" + attr.capitalize(), str(attributes[attr]))
		elif name == "server":
			self.url = str(attributes["url"])
			self.port = int(attributes["port"])
			self.channel = str(attributes["channel"])
			try:
				self.bind = str(attributes["bind"])
			except:
				pass
		elif name == "logic":
			self.logics_startup.append(str(attributes["name"]))
	
	def endElement(self, name):
		self.currentPath = self.currentPath[:self.currentPath.rfind("/%s" % name)+1]
